package com.honey.mybatis.generator.mappper;

import java.util.List;

import com.honey.compilation.xml.XmlElement;
import com.honey.core.dbmapping.introspect.IntrospectSchemaColumn;
import com.honey.core.dbmapping.introspect.IntrospectTableColumn;
import com.honey.core.dbmapping.structure.Column;
import com.honey.core.dbmapping.structure.Schema;
import com.honey.core.dbmapping.structure.Table;
import com.honey.core.dbmapping.structure.TableColumn;
import com.honey.mybatis.generator.MybatisPlugin;

public class UpdateByPrimaryKeySelective extends AbstractMybatisMapper{

	public UpdateByPrimaryKeySelective(MybatisPlugin belongPlugin) {
		super(belongPlugin);
	}

	public void appendElement(XmlElement parent, Schema schema, IntrospectSchemaColumn introspectSchemaColumn ){
		IntrospectTableColumn introspectTableColumn = null;
		if( schema instanceof Table ){
			introspectTableColumn = (IntrospectTableColumn)introspectSchemaColumn;
		}else{
			return ;
		}
		
		parent.addNewLine();
		parent.addComments(
				"按照主键更新不为空的记录,\"null\"值和主键不被更新"
		);
		XmlElement update = new XmlElement(parent,"update")
		.addAttribute("id",MapperConstant.UPDATE_BY_PRIMARY_KEY_SELECTIVE_MAPPER_ID)
		.addAttribute("parameterType",super.getEntityPrimitiveClassType(schema).getLongName())
		.addAttribute("timeout", mybatisPlugin.getConnectionTimeOut())
		.addAttribute("flushCache", "true")
		.addTextElement("UPDATE " + schema.getName())
		;
		
		XmlElement set = new XmlElement(update ,"set");
		
		List<Column> columns = introspectTableColumn.allColumns();
		String modelPackage = super.getModelPrimitiveClassType(schema).getLongName();
		for(Column column : columns ){
			TableColumn tc =(TableColumn)column;
			if(tc.isPrimaryKey()) continue;
			String fieldName =super.getFieldName(column);
			String typeHandler="";
			if( tc.getEnumSchema() != null){
				typeHandler=",typeHandler=" + modelPackage ;
			}
			set.addTextElement("<if test=\""+fieldName+" != null\" >"+ column.getName() +" = #{"+fieldName+",jdbcType="+JdbcTypeName.getJdbcTypeName(column.getJdbcType())+typeHandler+"},</if>");
		}
		List<TableColumn> primaryKeyList = introspectTableColumn.primaryKeyColumns();
		addPrimaryKeyConditionElement(update, primaryKeyList,introspectSchemaColumn.allColumns());
	}
}
